package com.member.web.controller.shop;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.annotation.Log;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.domain.R;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.BusinessType;
import com.member.common.utils.fy.HttpUtil;
import com.member.common.utils.fy.SignatureUtils;
import com.member.common.utils.poi.ExcelUtil;
import com.member.shop.domain.SysBizGoods;
import com.member.shop.domain.SysBizShopCertification;
import com.member.shop.domain.SysBizUserAddress;
import com.member.shop.dto.UserAddressDelExpDto;
import com.member.shop.dto.UserAddressExpDto;
import com.member.shop.service.ISysBizShopCertificationService;
import com.member.shop.service.ISysBizUserAddressService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【地址】控制器
 *
 * @author lixinchen
 * @version 1.0
 * @date 2024-01-09
 **/
@RestController
@RequestMapping("/shop/address")
public class SysBizUserAddressController extends BaseController {
    @Resource
    private ISysBizUserAddressService sysBizUserAddressService;


    @Value("${mall.order.merchantUrl}")
    private String merchantUrl;

    @Value("${mall.order.deleteMerchantUrl}")
    private String deleteMerchantUrl;

    @Value("${mall.order.privateKey}")
    private String privateKey;


    @Resource
    private ISysBizShopCertificationService sysBizShopCertificationService;

    /**
     * 查询地址列表
     */
    @PreAuthorize("@ss.hasPermi('shop:address:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBizUserAddress sysBizUserAddress) {
        setTenantId(sysBizUserAddress);
        startPage();
        List<SysBizUserAddress> list = sysBizUserAddressService.selectSysBizUserAddressList(sysBizUserAddress);
        return getDataTable(list);
    }

    private void setTenantId(SysBizUserAddress sysBizUserAddress) {
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            sysBizUserAddress.setTenantId(tenantId);
        }
    }

    /**
     * 导出地址列表
     */
    @PreAuthorize("@ss.hasPermi('shop:address:export')")
    @Log(title = "地址", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBizUserAddress sysBizUserAddress) {
        setTenantId(sysBizUserAddress);
        List<SysBizUserAddress> list = sysBizUserAddressService.selectSysBizUserAddressList(sysBizUserAddress);
        ExcelUtil<SysBizUserAddress> util = new ExcelUtil<SysBizUserAddress>(SysBizUserAddress.class);
        util.exportExcel(response, list, "地址数据");
    }

    /**
     * 获取地址详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:address:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysBizUserAddressService.selectSysBizUserAddressById(id));
    }

    /**
     * 新增地址
     */
    @PreAuthorize("@ss.hasPermi('shop:address:add')")
    @Log(title = "地址", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBizUserAddress sysBizUserAddress) {
        return toAjax(sysBizUserAddressService.insertSysBizUserAddress(sysBizUserAddress));
    }

    /**
     * 修改地址
     */
    @PreAuthorize("@ss.hasPermi('shop:address:edit')")
    @Log(title = "地址", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBizUserAddress sysBizUserAddress) {
        return toAjax(sysBizUserAddressService.updateSysBizUserAddress(sysBizUserAddress));
    }

    /**
     * 删除地址
     */
    @PreAuthorize("@ss.hasPermi('shop:address:remove')")
    @Log(title = "地址", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) {
//            UserAddressDelExpDto userAddressDelExpDto = new UserAddressDelExpDto();
//            userAddressDelExpDto.setAddressId(String.valueOf(id));
//            // 时间戳
//            String timeStamp = String.valueOf(System.currentTimeMillis());
//
//            // 签名（假设使用 SHA-256 对 data 和 timeStamp 进行签名）
//            String sign = null;
//            try {
//                sign = SignatureUtils.signWithSHA1(JSON.toJSONString(userAddressDelExpDto), SignatureUtils.getPrivateKey(privateKey));
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//            // 请求体
//            Map<String, Object> requestBody = new HashMap<>();
//            requestBody.put("timeStamp", timeStamp);
//            requestBody.put("sign", sign);
//            requestBody.put("data", JSON.toJSONString(userAddressDelExpDto));
//
//            // 发送 POST 请求
//            String response = HttpUtil.postJson(deleteMerchantUrl, JSON.toJSONString(requestBody));
//            // 解析响应
//            JSONObject jsonResponse = JSON.parseObject(response);
//            int code = jsonResponse.getIntValue("code");
            sysBizUserAddressService.removeErpAddress(id);
        }

        return toAjax(sysBizUserAddressService.deleteSysBizUserAddressByIds(ids));
    }
}
